<template>
  <div>
    <a-spin :loading="confirmLoading">
      <a-row class="header__action">
        <a-col :span="4">
          <a-select v-model="form.masterMeterId">
            <a-option value="">主表</a-option>
            <a-option
              v-for="item in subMeterOptions?.filter(e => e.selected)"
              :key="item.formId"
              :value="item.formId">
              {{ item.formName }}
            </a-option>
          </a-select>
        </a-col>
        <a-col :span="4" style="display: inline-flex">
          <span class="header__in-text">与</span>
          <a-select v-model="form.subMeterId" placeholder="请选择" allow-search :filter-option="filterOption">
            <a-option
              v-for="item in subMeterOptions"
              :key="item.formId"
              :value="item.formId">
              {{ item.formName }}
            </a-option>
          </a-select>
        </a-col>
        <a-col :span="2">
          <a-button type="primary" class="header__add-button" @click="queryMeter(true)">新增表外键关联</a-button>
        </a-col>
      </a-row>
      <a-form :model="dataObj" ref="exKeyFrom">
        <a-col
          class="main__table"
          v-for="(item,index) in dataObj.tableExConfig"
          :key="index">
          <h3>
            {{ item.title }}:
            <a-button type="primary" style="margin-right: 10px" @click.stop="handleEditKeys(index,item)">编辑外键关联</a-button>
            <a-button type="danger" @click.stop="handleDelete(index,item)">删除关联表</a-button>
          </h3>

          <a-table
            :columns="item.columns"
            :data="item.data"
            row-key="cid"
            :pagination="false"
            bordered
          >
            <template #masterMeterName="{ record }">
              <a-form-item v-if="!item.masterMeterId">
                {{ dataObj.pageData.find(c => c.cid === record.cid)?.formData.name }}
              </a-form-item>
              <a-form-item v-else>
                {{ record?.masterMeter?.name || '' }}
              </a-form-item>
            </template>
            <template #masterMeterDataIndex="{ record }">
              <a-form-item v-if="!item.masterMeterId">
                {{ dataObj.pageData.find(c => c.cid === record.cid )?.formData.dataIndex }}
              </a-form-item>
              <a-form-item v-else>
                {{ record?.masterMeter?.dataIndex || '' }}
              </a-form-item>
            </template>
            <template #key="{ record, rowIndex: meterIndex }" >
              <a-form-item
                :field="`tableExConfig[${index}].data[${meterIndex}].subMeter.dataIndex`"
                :rules="rules.dataIndex">
                <a-select v-model="record.subMeter.dataIndex" @change="changeSubMeterName($event,item,record)" placeholder="请选择">
                  <a-option
                    v-for="option in item.keyOptions"
                    :key="option.dataIndex"
                    :value="option.dataIndex">
                    {{ option.name }}
                  </a-option>
                </a-select>
              </a-form-item>
            </template>
            <template #displayField>
              <a-form-item>
                <a-select
                  multiple
                  placeholder="请选择"
                  v-model="item.selectedShowFields"
                  @change="values => changeShowFields(values,item)"
                >
                  <a-option
                    v-for="subMeter in item.keyOptions"
                    :key="subMeter.dataIndex"
                    :value="subMeter.dataIndex"
                  >
                    {{ subMeter.name }}
                  </a-option>
                </a-select>
              </a-form-item>
              <draggable v-model="item.selectedShowFields" @end="changeShowFields(item.selectedShowFields,item)">
                <a-form-item
                  style="float: left;width: 24.5%;margin-right: 0.5%"
                  v-for="(field,fieldIndex) in item.displayFields"
                  :key="field.dataIndex"
                  :field="`tableExConfig[${index}].displayFields[${fieldIndex}].anotherName`"
                  :rules="rules.anotherName"
                >
                  <div style="display: inline-flex;align-items: center;width: 100%">
                    <a-input
                      v-model="field.anotherName"
                      :placeholder="`输入${field.name}的别名`"
                      @change="onChange(field,item,fieldIndex)"
                    ></a-input>
                  </div>
                </a-form-item>
              </draggable>
            </template>
            <template #displayWay>
              <a-form-item>
                <a-select v-model="item.displayWay" placeholder="请选择">
                  <a-option v-for="display in displayWayList" :key="display.key" :value="display.key">
                    {{ display.label }}
                  </a-option>
                </a-select>
              </a-form-item>
            </template>
            <template #action="{ rowIndex: tIndex }">
              <a-form-item>
                <a class="g-delete-button" @click="handleDeleteItem(index,tIndex)">删除</a>
              </a-form-item>
            </template>
          </a-table>
        </a-col>
      </a-form>
    </a-spin>

    <a-modal
      title="绑定外键字段"
      :width="600"
      v-model:visible="visible"
      :ok-loading="confirmLoading2"
      :align-center="true"
      unmount-on-close
      :mask-closable="false"
      ok-text="确认"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :loading="confirmLoading2">
        <a-form ref="keyForm" :model="form" :rules="rules">
          <a-form-item label="选择绑定外键字段" :field="`selectFields`">
            <a-select style="width: 100%" label-in-value v-model="form.selectFields">
              <a-option v-for="item in form.fieldOptions" :key="item.dataIndex" :value="item.dataIndex">
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { nanoid } from 'nanoid'
/*
* params {}
* masterMeterTitle 主表名称
* subMeterTitle 附表名称
* rowSpan 多少条外键
* */
const setColumn = (masterMeterTitle, subMeterTitle) => [
  {
    title: masterMeterTitle,
    dataIndex: 'masterMeter',
    children: [
      {
        title: '字段名称',
        width: 180,
        dataIndex: 'masterMeter.name',
        slotName: 'masterMeterName'
      },
      {
        title: '数据绑定key',
        width: 180,
        dataIndex: 'masterMeter.dataIndex',
        slotName: 'masterMeterDataIndex'
      }
    ]
  },
  {
    title: `${subMeterTitle}`,
    dataIndex: 'subMeter',
    children: [
      {
        title: '外键绑定',
        width: 180,
        dataIndex: 'subMeter.dataIndex',
        slotName: 'key'
      },
      {
        title: '外键展示字段',
        dataIndex: 'subMeter.list',
        slotName: 'displayField',
        customCell: (record, rowIndex) => {
          if (rowIndex === 0) {
            return {
              attrs: {
                rowSpan: 1000,
                colSpan: 1
              }
            }
          } else {
            return {
              style: {
                display: 'none'
              }
            }
          }
        }
      },
      {
        title: '处理',
        width: 120,
        dataIndex: 'subMeter.displayWay',
        slotName: 'displayWay',
        customCell: (record, rowIndex) => {
          if (rowIndex === 0) {
            return {
              attrs: {
                rowSpan: 1000,
                colSpan: 1
              }
            }
          } else {
            return {
              style: {
                display: 'none'
              }
            }
          }
        }
      }
      // {
      //   title: '操作',
      //   width: 60,
      //   dataIndex: 'subMeter.action',
      //   slotName: 'action'
      // }
      ]
  }]
export default {
  name: 'ExternalKey',
  data () {
    return {
      visible: false,
      confirmLoading2: false,
      confirmLoading: false,
      subMeterOptions: [], // 副表的选项
      rules: {
        selectFields: [{ required: true, message: '必填', type: 'object' }],
        displayFields: [],
        selectedShowFields: [],
        anotherName: [{ required: true, message: '必填' }],
        dataIndex: [{ required: true, message: '必填' }]
      },
      displayWayList: [
        { label: '平铺', key: 'column' },
        { label: '替换', key: 'replace' }
        // { label: '内嵌', key: 'inner' }
      ],
      form: {
        isAddKey: true, // 是否为新增
        masterMeterId: '', // 主表
        subMeterId: '', // 副表
        selectFields: {}, // 本次选择的处理字段
        fieldOptions: [],
        keyOptions: [] // 外键选择项
      }
    }
  },
  inject: ['dataObj'],
  methods: {
    // 下拉框按label搜索
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    changeShowFields (values, item) {
      const { keyOptions } = item
      const data = values.map(value => {
        return keyOptions.find(e => e.dataIndex === value)
      })
      Object.assign(item, { displayFields: data })
    },
    changeSubMeterName (value, item, record) {
      // 给name赋值
      const data = item.keyOptions.find(e => e.dataIndex === value)
      record.subMeter.name = data.name
      // 取字段类型，给主表字段赋值字段类型
      const { columnType } = data
      const { formData } = this.dataObj.pageData.find(c => c.cid === record.cid)
      formData.dataType = columnType || 'string'
    },
    onChange (field, item, fieldIndex) {
      const data = item.keyOptions.find(cc => cc.dataIndex === field.dataIndex) || {}
      // 配置展示字段，需要用到哪些字段
      const { columnName, columnType, typeFormat } = data
      Object.assign(item.displayFields[fieldIndex], { columnName, columnType, typeFormat })
    },
    // 查询数据表的字段有哪些
    async queryMeter (isAddKey) {
      try {
        this.form.isAddKey = isAddKey
        if (!this.form.subMeterId) {
          this.$message.warn('请选择关联表')
          return
        }
        if (this.form.masterMeterId === this.form.subMeterId) {
          this.$message.warn('不能关联自身')
          return
        }
        this.visible = true
        // 取出所有主表已选的外键字段
        const list = this.dataObj.tableExConfig.map(item => {
            const dataIndex = item.data[0].masterMeter.dataIndex
          if (!item.masterMeterName && dataIndex) {
            return dataIndex
          }
        })
        console.log(list)
        // 返回外键除已选外的其它可选字段
        if (!this.form.masterMeterId) { // 关联主表
          this.form.fieldOptions = this.dataObj.pageData?.map(item => {
            // if (!list.some(value => item.formData.dataIndex === value)) {
             return {
               name: item.formData.name,
               dataIndex: item.formData.dataIndex
             }
           // }
          }).filter(Boolean)
        } else {
          const { masterMeterId } = this.form
          const result = await this.$http.get('/foreignKey/queryTableColumn', { params: { formId: masterMeterId } })
          this.form.dbNameMaster = this.subMeterOptions.find(item => item.formId === masterMeterId).dbName
          const list = this.dataObj.tableExConfig.map(item => {
            const dataIndex = item.data[0].masterMeter.dataIndex
            if (this.form.masterMeterId === item.masterMeterId && dataIndex) {
              return dataIndex
            }
          })
          console.log('chu', list)
          this.form.fieldOptions = result.data?.map(item => {
            if (!list.some(value => item.columnKey === value)) {
              return {
                ...item,
                name: item.columnName,
                dataIndex: item.columnKey
              }
            }
          }).filter(Boolean)
        }
      } catch (e) {
        console.error('请求失败', e)
      }
    },
    // 清空form数据
    clearFormData () {
      Object.keys(this.form).forEach(key => {
        if (key === 'selectFields') {
          this.form[key] = []
        } else {
          this.form[key] = ''
        }
      })
    },
    handleOk () {
      this.$refs.keyForm.validate(async valid => {
        if (valid) {
          try {
            const { masterMeterId, subMeterId, meterIndex, selectFields } = this.form

            this.confirmLoading2 = true
            // const masterMeterRequest = () => this.$http.get('/foreignKey/queryTableColumn', { params: { formId: this.form.masterMeterId } })
            const subMeterRequest = () => this.$http.get('/foreignKey/queryTableColumn', { params: { formId: this.form.subMeterId } })
            const result = await subMeterRequest()
            const subMeterObject = this.subMeterOptions.find(item => item.formId === this.form.subMeterId)
            let dbNameMaster, masterFormName
            const dbName = subMeterObject?.dbName
            const subFormName = subMeterObject.formName
            if (masterMeterId) {
              const master = this.subMeterOptions.find(item => item.formId === masterMeterId)
              dbNameMaster = master.dbName
              masterFormName = master.formName
            }
            const dataContent = {
              title: `${masterFormName || '主表'}与` + subFormName + '的关联',
              masterMeterId: masterMeterId,
              masterMeterName: dbNameMaster || '',
              masterFormName: masterFormName || '',
              subMeterId: subMeterId,
              subMeterName: dbName,
              subFormName,
              displayWay: 'column',
              displayFields: [],
              selectedShowFields: [],
              selectFields: selectFields,
              columns: setColumn(masterFormName || '主表', subFormName),
              keyOptions: result.data?.map(item => ({
                ...item,
                name: item.columnName,
                dataIndex: item.columnKey,
                anotherName: item.columnName
              })),
              // 以前selectFields是多选的，现在是单选的
              data: [selectFields].map(item => {
                // const data = this.dataObj.tableExConfig[meterIndex]?.data
                // const oldData = (data && data.find(cc => cc.masterMeter.dataIndex === item.key))
                // if (!_.isEmpty(oldData)) return oldData // 如果有旧数据就返回，没有就塞新值
                return {
                  cid: !dbNameMaster ? this.dataObj.pageData.find(c => c.formData.dataIndex === item.key).cid : 'exKey_' + nanoid(10),
                  masterMeter: {
                    name: item.label,
                    dataIndex: item.key
                  },
                  subMeter: {
                    dataIndex: undefined,
                    name: undefined
                  }
                }
              })
            }

            if (this.form.isAddKey) {
              this.dataObj.tableExConfig.push(dataContent)
            } else {
              this.dataObj.tableExConfig.splice(meterIndex, 1, dataContent)
            }
            this.visible = false
            // 处理余下逻辑，1-可选表 2-清空数据
            subMeterObject.selected = true
            this.clearFormData()
          } catch (e) {
            console.error('请求失败', e)
          } finally {
            this.confirmLoading2 = false
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.clearFormData()
    },
    // 编辑时过滤数据
    filterMeterData () {
       // 过滤主表哪些已选
      this.dataObj.tableExConfig.forEach(async item => {
        const { masterFormName, subFormName } = item
        item.columns = setColumn(masterFormName || '主表', subFormName) // 设置columns

        if (item.masterMeterId) {
          const option = this.subMeterOptions.find(option => option.formId === item.masterMeterId)
          option && (option.selected = true)
        }
        if (item.subMeterId) {
          const option = this.subMeterOptions.find(option => option.formId === item.subMeterId)
          option && (option.selected = true)
          const result = await this.$http.get('/foreignKey/queryTableColumn', { params: { formId: item.subMeterId } })
          item.keyOptions = result.data.map(cc => ({
            ...cc,
            name: cc.columnName,
            dataIndex: cc.columnKey,
            anotherName: cc.columnName
          }))
        }
      })
    },
    // 编辑外键关联
    handleEditKeys (index, record) {
      // 获取data里面的字段赋值，打开编辑外键
      this.form.selectFields = record.data.map(item => ({ label: item.masterMeter.name, key: item.masterMeter.dataIndex }))[0]
      this.form.masterMeterId = record.masterMeterId
      this.form.subMeterId = record.subMeterId
      this.form.meterIndex = index
      this.queryMeter(false)
    },
    // 删除一行
    handleDeleteItem (index, tIndex) {
      this.dataObj.tableExConfig[index].data.splice(tIndex, 1)
    },
    // 删除关联表
    handleDelete (index, item) {
      const { subMeterId } = item
      this.dataObj.tableExConfig.splice(index, 1)
      const subMeter = this.subMeterOptions.find(item => item.formId === subMeterId)
      subMeter.selected = false
    },
    // 查询表有哪些表
    async queryTableList () {
      try {
        this.confirmLoading = true
        const result = await this.$http.post('/foreignKey/queryTableList', {})
        this.subMeterOptions = result.data
        const { formId } = this.dataObj.tableDesc
        // 有formId为编辑
        if (formId) {
          this.filterMeterData()
        }
      } catch (e) {
        console.error('请求失败', e)
      } finally {
        this.confirmLoading = false
      }
    }
  },
  created () {
    this.queryTableList()
  }
}
</script>

<style lang="less" scoped>
.header__action {
  .header__in-text {
    display: flex;
    align-items: center;
    margin-left: 10px;
    margin-right: 10px
  }

  .header__add-button {
    margin-left: 10px;
  }
}

.main__table {
  margin-top: 20px;
  //align-items: center;
}
</style>
